var app = getApp();

Page({
  data: {
    docList: [],
  },
  onLoad: function () {
    app.util.request({
    	url: "entry/wxapp/DownloadList",
    	success: (res) => {
        let doc_list = res.data.data.doc_list;
        for(let i = 0; i < doc_list.length; i++) {
          doc_list[i].size =  parseInt( doc_list[i].size / 1000 );
          doc_list[i].uploadtime = doc_list[i].uploadtime.split(" ")[0]
        }
    		this.setData({docList: doc_list})
    	}
    })
  },
  onShareAppMessage: function () {
    return {
      title: '重庆大学体育学院研究生支部委员会',
      path: 'cqdx_communist/pages/index/index'
    }
  },

  handleDownload(e) {
    console.log(e)
    let url = e.currentTarget.dataset.url;
    let index = e.currentTarget.dataset.index;
    let docId = e.currentTarget.dataset.id;

    let res = []
    for (let i = 0; i < this.data.docList.length; i++) {
      res.push(this.data.docList[i])
    }
    res[index].downloadnum++;
    this.setData({docList: res});



    app.util.request({
      url: "entry/wxapp/DownloadAdd",
      data: {
        docId: docId
      }
    })

    
    wx.downloadFile({
      url: url,
      success: function(res) {
        console.log('download: ', res)
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        if (res.statusCode === 200) {
          let filePath = res.tempFilePath
          wx.saveFile({
            tempFilePath: filePath,
            success: (res) => {
              console.log('savedata: ', res)
              wx.openDocument({
                filePath: res.savedFilePath,
              })
            }
          })
        }
      }
    })
  }
  
})
